package com.utils.commons;

import java.util.List;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;

/**
 * @author geliyang
 *
 * @param <T>
 */
public class PageUtils<T> {
	
	private int size;
	
	private int totalPages;
	
	private long totalElements;
	
	private List<T> content;
	
	public PageUtils (Page<T> pageable) {
		this.content = pageable.getContent();
		this.size = pageable.getSize();
		this.totalPages = pageable.getTotalPages();
		this.totalElements = pageable.getNumberOfElements();
	}
	
	public static<T> PageUtils<T> of(Page<T> pageable) {
		return new PageUtils<T>(pageable);
	}
	
	/**
	 * @param page 第一页:1   --不是查询时0的第一页
	 * @param size
	 * @param sort
	 * @return
	 */
	public static Pageable toPageable(Integer page, Integer size, Sort sort) {
		return PageRequest.of(getPageForQuery(page), getNonNullSize(size), sort);
	}
	
	/**
	 * @param page 第一页:1   --不是查询时0的第一页
	 * @param size
	 * @param sort
	 * @return
	 */
	public static Pageable toPageable(Integer page, Integer size) {
		return toPageable(getPageForQuery(page), getNonNullSize(size), Sort.unsorted());
	}
	
	/**
	 * @param page 第一页:1   --不是查询时0的第一页
	 * @param size
	 * @param sort
	 * @return
	 */
	public static Pageable toPageable(Integer page, Integer size, Direction direction, String... properties) {
		return PageRequest.of(getPageForQuery(page), getNonNullSize(size), direction, properties);
	}

	public int getSize() {
		return size;
	}

	public void setSize(int size) {
		this.size = size;
	}

	public long getTotalElements() {
		return totalElements;
	}

	public void setTotalElements(long totalElements) {
		this.totalElements = totalElements;
	}

	public List<T> getContent() {
		return content;
	}

	public void setContent(List<T> content) {
		this.content = content;
	}

	private static int getPageForQuery(Integer num) {
		return (num == null || num < 1) ? 0 : num - 1;
	}
	
	private static int getNonNullSize(Integer num) {
		return (num == null || num < 1) ? 10 : num;
	}

	public int getTotalPages() {
		return totalPages;
	}

	public void setTotalPages(int totalPages) {
		this.totalPages = totalPages;
	}

}
